<template>
  <div id="bodypage">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/homePage' }"><span id="mainpage">主页</span></el-breadcrumb-item>
      <el-breadcrumb-item>病例信息</el-breadcrumb-item>
      <el-breadcrumb-item><span>病例记录</span></el-breadcrumb-item>
    </el-breadcrumb>
    <div>
      <!-- 搜索页 -->
      <el-dialog title="请输入检索信息" v-dialogDrag :visible.sync="searchPage" width="450px" :before-close="handleClose" id="searchDialog">
        <el-form :model="searchData">
          <el-form-item label="牧户姓名" label-width="70px">
            <el-input type="text" autocomplete="off" v-model="searchData.userName"></el-input>
          </el-form-item>
          <el-form-item label="羊只编号" label-width="70px">
            <el-input type="number" autocomplete="off" v-model="searchData.sheepId"></el-input>
          </el-form-item>
          <el-form :model="searchData" :inline="true">
            <el-form-item label="时间" label-width="70px" style="margin-right: 0;">
              <el-input type="datetime-local" autocomplete="off" style="width: 9.9344rem;" placeholder="最小值"
                v-model="searchData.dateMin">
              </el-input>
            </el-form-item>
            <span style="margin: 0 5px; height: 40px; display: inline-block; line-height: 40px;">--</span>
            <el-form-item style="margin-right: 0;">
              <el-input type="datetime-local" autocomplete="off" style="width: 9.9344rem;" placeholder="最大值"
                v-model="searchData.dateMax">
              </el-input>
            </el-form-item>
          </el-form>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="searchPage = false">取 消</el-button>
          <el-button type="success" @click="searchInfo" @keyup.enter.native="searchInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 新增页 -->
      <el-dialog title="羊只病例记录表" v-dialogDrag :visible.sync="addPage" width="780px" :before-close="handleClose">
        <el-form :inline="true" :model="inputValue">
          <el-form-item label="羊只编号" label-width="140px">
            <el-input type="number" v-model="inputValue.sheepId"></el-input>
          </el-form-item>
          <el-form-item label="发病日期" label-width="140px">
            <el-input type="datetime-local" v-model="inputValue.date" style="width: 187px;"></el-input>
          </el-form-item>
          <el-form-item label="临床症状" label-width="140px">
            <el-input type="text" v-model="inputValue.symptom"></el-input>
          </el-form-item>
          <el-form-item label="诊断病名" label-width="140px">
            <el-input type="text" v-model="inputValue.diseaseName"></el-input>
          </el-form-item>
          <el-form-item label="处理方法" label-width="140px">
            <el-input type="text" v-model="inputValue.handlingMethod"></el-input>
          </el-form-item>
          <el-form-item label="用药名称" label-width="140px">
            <el-input type="text" v-model="inputValue.drugName"></el-input>
          </el-form-item>
          <el-form-item label="发病时长" label-width="140px">
            <el-input type="text" v-model="inputValue.morbidDate"></el-input>
          </el-form-item>
          <el-form-item label="治疗效果" label-width="140px">
            <el-select clearable v-model="inputValue.effect" placeholder="请选择" style="width: 187px;">
              <el-option v-for="item in inputValue.effectOptions" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" label-width="140px">
            <el-input type="text" v-model="inputValue.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addPage = false">取 消</el-button>
          <el-button type="success" @click="add">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 查看与编辑页 -->
      <el-dialog title="羊只病例记录表" v-dialogDrag :visible.sync="checkPage" width="780px" :before-close="handleClose">
        <el-form :inline="true" :model="row">
          <el-form-item label="羊只编号" label-width="140px">
            <el-input type="number" v-model="row.SHEEP_ID"></el-input>
          </el-form-item>
          <el-form-item label="发病日期" label-width="140px">
            <el-input type="datetime-local" v-model="row.FALL_ILL_DATE" style="width: 187px;"></el-input>
          </el-form-item>
          <el-form-item label="临床症状" label-width="140px">
            <el-input type="text" v-model="row.SYMPTOM"></el-input>
          </el-form-item>
          <el-form-item label="诊断病名" label-width="140px">
            <el-input type="text" v-model="row.DISEASE_NAME"></el-input>
          </el-form-item>
          <el-form-item label="处理方法" label-width="140px">
            <el-input type="text" v-model="row.HANDLING_METHOD"></el-input>
          </el-form-item>
          <el-form-item label="用药名称" label-width="140px">
            <el-input type="text" v-model="row.DRUG_NAME"></el-input>
          </el-form-item>
          <el-form-item label="发病时长" label-width="140px">
            <el-input type="text" v-model="row.MORBID_DATE"></el-input>
          </el-form-item>
          <el-form-item label="治疗效果" label-width="140px">
            <el-select clearable v-model="row.THERAPEUTIC_EFFECT" placeholder="请选择" style="width: 187px;">
              <el-option v-for="item in modifyData.effectOptions" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="牧户姓名" label-width="140px">
            <el-input type="text" v-model="row.NAME"></el-input>
          </el-form-item>
          <el-form-item label="备注" label-width="140px">
            <el-input type="text" v-model="row.REMARK"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button id="checkPageButton" type="danger" @click="update">修 改</el-button>
          <el-button type="success" @click="checkPage = false">关 闭</el-button>
        </span>
      </el-dialog>
      <div id="headerArea">
        <h2 style="margin:10px 0 10px 10px; display: inline-block;">羊只病历记录表</h2>
        <div>
          <input v-show="false" ref="elementData" type="file" @change="importExcel(this)" />
          <el-button type="success" size="mini" @click="$refs.elementData.click()">导入
          </el-button>
          <el-button type="success" size="mini" style="margin-right: 15px;" @click="exportExcel">导出
          </el-button>
        </div>
      </div>
      <template>
        <!--这里v-if-->
        <el-button @click="addPage = true" round type="success" slot="append" icon="el-icon-edit"
          style="margin: 10px 10px 10px 10px;">新增</el-button>
        <el-button round type="success" slot="append" icon="el-icon-search" style="margin: 10px 0 10px 10px;"
          @click="searchPage = true">搜索</el-button>
      </template>
      <!-- 表格区 -->
      <el-table @sort-change="sortTable" max-height="400" :data="tableData" :row-class-name="tableRowClassName"
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}" border @row-click="getDetails"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}" row-key="ID">
        <!--.slice((queryInfo.pagenum-1)*5,queryInfo.pagenum*5)-->
        <el-table-column type="selection" width="35"></el-table-column>
        <el-table-column width="80px"><template slot-scope="scope">{{scope.$index+1}}</template></el-table-column>
        <el-table-column type="expand">
          <div slot-scope="props" style="margin-left: 20px;">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="ID:">
                <span>{{ props.row.ID }}</span>
              </el-form-item>
              <el-form-item label="羊只编号:">
                <span>{{ props.row.SHEEP_ID }}</span>
              </el-form-item>
              <el-form-item label="发病日期:">
                <span>{{ props.row.FALL_ILL_DATE }}</span>
              </el-form-item>
            </el-form>
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="临床症状:">
                <span>{{ props.row.SYMPTOM }}</span>
              </el-form-item>
              <el-form-item label="诊断病名:">
                <span>{{ props.row.DISEASE_NAME }}</span>
              </el-form-item>
              <el-form-item label="处理方法:">
                <span>{{ props.row.HANDLING_METHOD }}</span>
              </el-form-item>
            </el-form>
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="用药名称:">
                <span>{{ props.row.DRUG_NAME }}</span>
              </el-form-item>
              <el-form-item label="发病时长:">
                <span>{{ props.row.MORBID_DATE }}</span>
              </el-form-item>
              <el-form-item label="治疗效果:">
                <span>{{ props.row.THERAPEUTIC_EFFECT }}</span>
              </el-form-item>
            </el-form>
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="牧户姓名:">
                <span>{{ props.row.NAME }}</span>
              </el-form-item>
              <el-form-item label="备注:">
                <span>{{ props.row.REMARK }}</span>
              </el-form-item>
            </el-form>
          </div>
        </el-table-column>
        <el-table-column sortable="custom" prop="ID" label="ID" align="center"></el-table-column>
        <el-table-column min-width="110px" sortable="custom" prop="SHEEP_ID" label="羊只编号" align="center">
        </el-table-column>
        <el-table-column min-width="200px" sortable="custom" prop="FALL_ILL_DATE" label="发病日期" align="center">
        </el-table-column>
        <el-table-column min-width="150px" prop="SYMPTOM" label="临床症状" align="center"></el-table-column>
        <el-table-column min-width="150px" prop="DISEASE_NAME" label="诊断病名" align="center"></el-table-column>
        <el-table-column min-width="150px" prop="HANDLING_METHOD" label="处理方法" align="center"></el-table-column>
        <el-table-column min-width="150px" prop="DRUG_NAME" label="用药名称" align="center"></el-table-column>
        <el-table-column min-width="110px" sortable="custom" prop="MORBID_DATE" label="发病时长" align="center">
        </el-table-column>
        <el-table-column min-width="100px" prop="THERAPEUTIC_EFFECT" label="治疗效果" align="center">
        </el-table-column>
        <el-table-column min-width="100px" prop="NAME" label="牧户姓名" align="center"></el-table-column>
        <el-table-column min-width="100px" prop="REMARK" label="备注" align="center"></el-table-column>
        <el-table-column prop="Operate" label="操作" align="center" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button-group>
              <el-tooltip class="item" effect="dark" content="查看编辑" placement="top-start" :enterable="false">
                <el-button @click="checkPage = true" type="success" icon="el-icon-edit"></el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination style="padding-right: 0;" prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" layout="total, prev, pager, next, jumper" :total="queryInfo.total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        searchData: {
          userName: '',   //牧户姓名
          sheepId: '',      //羊只编号
          dateMax: '',      //时间最大值
          dateMin: '',      //时间最小值
        },
        tableData: [],
        searchPage: false,
        addPage: false,
        checkPage: false,
        row: {},
        inputValue: {
          sheepId: '',         //羊只编号
          //上面为索引值
          //下面为修改值
          date: '',         //发病日期
          symptom: '',       //临床症状
          diseaseName: '',    //诊断病名
          handlingMethod: '', //处理方法
          drugName: '',       //用药名称
          morbidDate: '',    //发病时长
          effectOptions: [{
            value: '已康复',
            label: '已康复'
          }, {
            value: '康复中',
            label: '康复中'
          }, {
            value: '已去世',
            label: '已去世'
          }],
          effect: '',         //治疗效果(已康复，康复中，已去世)
          remark: '',             //备注
        },
        queryInfo: {
          pagenum: 1, // 当前页码
          total: 0
        },
        sortValue: {
          sortLowNum: '',
          ISAsc: ''
        },
        modifyData: {
          effectOptions: [{
            value: '已康复',
            label: '已康复'
          }, {
            value: '康复中',
            label: '康复中'
          }, {
            value: '已去世',
            label: '已去世'
          }],
        },
        isSearch: false,
        exportData: null
      }
    },
    mounted() {
      this.handleRequestGetInfo()
    },
    activated() {
      // if (this.$store.state.diameterMax && this.$store.state.diameterMin) {
      //   this.searchData.diameterMax = this.$store.state.diameterMax;
      //   this.searchData.diameterMin = this.$store.state.diameterMin;
      //   this.searchInfo()
      //   this.$store.commit("emptyDiameter"); //重置vuex里存储的羊只编号
      // }
    },
    methods: {
      // 排序
      sortTable({ column, prop, order }) {
        switch (prop) {
          case 'ID': this.sortValue.sortLowNum = 1; break;
          case 'SHEEP_ID': this.sortValue.sortLowNum = 2; break;
          case 'FALL_ILL_DATE': this.sortValue.sortLowNum = 3; break;
          case 'MORBID_DATE': this.sortValue.sortLowNum = 8; break;
        }
        if (order == "ascending") {
          this.sortValue.ISAsc = 1;
          console.log("升序了");
        } else if (order == "descending") {
          this.sortValue.ISAsc = 0;
          console.log("降序了");
        } else {
          this.sortValue.ISAsc = '';
          console.log("取消排序");
        }
        Object.keys(this.searchData).forEach(key => { if (this.searchData[key] != '') this.isSearch = true })
        if (this.isSearch) this.searchInfo()
        else this.handleRequestGetInfo()
      },

      //进入页面默认加载
      async handleRequestGetInfo() {
        let { data } = await this.$axios({
          method: 'post',
          url: '/casesSalesInfo/case',
          data: {
            sortLowNum: this.sortValue.sortLowNum,
            ISAsc: this.sortValue.ISAsc,
            page: this.queryInfo.pagenum,
            isPage: 1
          }
        })
        console.log(data);
        //如果获取成功
        if (data.code === 0) {
          this.$message({
            type: 'success',
            message: data.msg,
            duration: 1500
          })
        } else {
          //获取失败
          return this.$message({
            type: 'error',
            message: data.msg,
            duration: 1500
          })
        }
        this.tableData = data.data.result
        this.queryInfo.total = data.data.countAll
      },
      //查询
      async searchInfo() {
        console.log(this.searchData, this.queryInfo.pagenum);
        let { data } = await this.$axios({
          method: 'post',
          url: '/casesSalesInfo/case/find',
          data: {
            //下面三个参数 只可有一个
            userName: this.searchData.userName,   //牧户姓名
            sheepId: this.searchData.sheepId,      //羊只编号
            dateMax: this.searchData.dateMax,      //时间最大值
            dateMin: this.searchData.dateMin,      //时间最小值      //公羊编号
            sortLowNum: this.sortValue.sortLowNum,   //第几列的排序数，从左往右，从1开始
            ISAsc: this.sortValue.ISAsc,         //增还是减  1为增，0为减
            page: this.queryInfo.pagenum,          //页码
            isPage: 1
          }
        })
        //如果查询成功
        console.log(data);
        if (data.code === 0) {
          // this.$message({
          //   type: 'success',
          //   message: data.msg,
          //   duration: 1500
          // })
        } else {
          //查询失败
          return this.$message({
            type: 'error',
            message: data.msg,
            duration: 1500
          })
        }
        this.searchPage = false
        this.tableData = data.data.result
        this.queryInfo.total = data.data.countAll
      },

      //新增
      async add() {
        console.log(this.inputValue);
        console.log("添加开始");
        let { data } = await this.$axios({
          method: 'post',
          url: '/casesSalesInfo/case/add/single',
          data: {
            sheepId: this.inputValue.sheepId,         //羊只编号
            //上面为索引值
            //下面为修改值
            date: this.inputValue.date,         //发病日期
            symptom: this.inputValue.symptom,       //临床症状
            diseaseName: this.inputValue.diseaseName,    //诊断病名
            handlingMethod: this.inputValue.handlingMethod, //处理方法
            drugName: this.inputValue.drugName,       //用药名称
            morbidDate: this.inputValue.morbidDate,     //发病时长
            effect: this.inputValue.effect,         //治疗效果(已康复，康复中，已去世)
            remark: this.inputValue.remark             //备注
          }
        })
        console.log(data);
        console.log("添加结束");
        //如果添加成功
        if (data.code === 0) {
          this.$message({
            type: 'success',
            message: data.msg,
            duration: 1500
          })
        } else {
          //添加失败
          return this.$message({
            type: 'error',
            message: data.msg,
            duration: 1500
          })
        }
        this.addPage = false
        Object.keys(this.searchData).forEach(key => { if (this.searchData[key] != '') this.isSearch = true })
        if (this.isSearch) this.searchInfo()
        else this.handleRequestGetInfo()
      },

      //批量导入
      async importExcelData(excelData) {
        console.log(excelData);
        let { data } = await this.$axios({
          method: 'post',
          url: '/casesSalesInfo/case/add/batch',
          data: {
            arr: excelData
          }
        })
        //如果导入成功
        if (data.code === 0) {
          this.$message({
            type: 'success',
            message: data.msg,
            duration: 3000
          })
        } else {
          //导入失败
          return this.$message({
            type: 'error',
            message: data.msg,
            duration: 3000
          })
        }
        Object.keys(this.searchData).forEach(key => { if (this.searchData[key] != '') this.isSearch = true })
        if (this.isSearch) this.searchInfo()
        else this.handleRequestGetInfo()
      },

      //编辑更新
      async update() {
        console.log("更新开始");
        console.log(this.row);
        let { data } = await this.$axios({
          method: 'post',
          url: '/casesSalesInfo/case/update',
          data: {
            id: this.row.ID,     //该条信息的编号
            sheepId: this.row.SHEEP_ID,         //羊只编号
            //上面是索引
            //下面是修改内容 不可都为空
            date: this.row.FALL_ILL_DATE,         //发病日期
            symptom: this.row.SYMPTOM,       //临床症状
            diseaseName: this.row.DISEASE_NAME,    //诊断病名
            handlingMethod: this.row.HANDLING_METHOD, //处理方法
            drugName: this.row.DRUG_NAME,       //用药名称
            morbidDate: this.row.MORBID_DATE,     //发病时长
            effect: this.row.THERAPEUTIC_EFFECT,         //治疗效果(已康复，康复中，已去世)
            remark: this.row.REMARK,             //备注                 //备注
          }
        })
        console.log("更新结束");
        console.log(data);
        //如果更新成功
        if (data.code === 0) {
          this.$message({
            type: 'success',
            message: data.msg,
            duration: 1500
          })
        } else {
          //更新失败
          return this.$message({
            type: 'error',
            message: data.msg,
            duration: 1500
          })
        }
        Object.keys(this.searchData).forEach(key => { if (this.searchData[key] != '') this.isSearch = true })
        if (this.isSearch) this.searchInfo()
        else this.handleRequestGetInfo()
        this.checkPage = false
      },

      //通用弹出框函数
      handleClose(done) {
        this.$messagebox.confirm('确认关闭？')
          .then(_ => { done() })
          .catch(_ => { })
      },

      // 改变页码值
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage;
        Object.keys(this.searchData).forEach(key => { if (this.searchData[key] != '') this.isSearch = true })
        if (this.isSearch) {
          this.searchInfo()
          this.isTurnThePage = true
        }
        else {
          this.handleRequestGetInfo()
        }
      },

      //获取点击行数据并赋值给row
      getDetails(row) {
        this.row = JSON.parse(JSON.stringify(row)) // 调用JSON方法防止内存冲突
      },

      //改变已死亡或已售出的羊只表格颜色
      tableRowClassName({ row, rowIndex }) {
        if (row.THERAPEUTIC_EFFECT == '已去世') {
          return 'die-row';
        }
        return '';
      },

      //导出Excel表格
      async exportExcel() {
        Object.keys(this.searchData).forEach(key => { if (this.searchData[key] != '') this.isSearch = true })
        if (this.isSearch) {
          let { data } = await this.$axios({
            method: 'post',
            url: '/casesSalesInfo/case/find',
            data: {
              //下面三个参数 只可有一个
              userName: this.searchData.userName,   //牧户姓名
              sheepId: this.searchData.sheepId,      //羊只编号
              dateMax: this.searchData.dateMax,      //时间最大值
              dateMin: this.searchData.dateMin,      //时间最小值      //公羊编号
              sortLowNum: this.sortValue.sortLowNum,   //第几列的排序数，从左往右，从1开始
              ISAsc: this.sortValue.ISAsc,         //增还是减  1为增，0为减
              page: this.queryInfo.pagenum,          //页码
              isPage: 0
            }
          })
          this.exportData = data.data.result
        }
        else {
          let { data } = await this.$axios({
            method: 'post',
            url: '/casesSalesInfo/case',
            data: {
              sortLowNum: this.sortValue.sortLowNum,
              ISAsc: this.sortValue.ISAsc,
              page: this.queryInfo.pagenum,
              isPage: 0
            }
          })
          this.exportData = data.data.result
        }
        const exportData = JSON.parse(JSON.stringify(this.exportData).replace(/SHEEP_ID/g, "羊只编号")
          .replace(/FALL_ILL_DATE/g, "发病日期").replace(/SYMPTOM/g, "临床症状").replace(/DISEASE_NAME/g, "诊断病名")
          .replace(/HANDLING_METHOD/g, "处理方法").replace(/DRUG_NAME/g, "用药名称").replace(/MORBID_DATE/g, "发病时长")
          .replace(/THERAPEUTIC_EFFECT/g, "治疗效果").replace(/NAME/g, "牧户姓名").replace(/REMARK/g, "备注"));
        // console.log(this.tableData);
        // console.log(obj);
        let data = exportData;
        //1. 新建一个工作簿
        let workbook = this.$XLSX.utils.book_new();
        //2. 把json对象转成工作表
        let sheet = this.$XLSX.utils.json_to_sheet(data);
        //3.在工作簿中添加工作表
        this.$XLSX.utils.book_append_sheet(workbook, sheet, '羊只病历记录表'); //工作簿名称
        //4.输出工作表,由文件名决定的输出格式
        this.$XLSX.writeFile(workbook, '羊只病历记录表(导出日期：' + this.$moment().format("YYYY年MM月DD日 HH时mm分ss秒 dddd") + ').xlsx'); // 保存的文件名
      },

      //导入Excel表格数据
      importExcel() {
        let obj = this.$refs.elementData
        let file = obj.files[0];
        if (!obj.files || file == undefined) return
        let $this = this //将vm的值赋值给变量$this
        {
          let reader = new FileReader();
          reader.onload = function (e) {
            let data = e.target.result;
            let tempData = $this.$XLSX.read(data, { type: 'binary' });
            $this.importData = JSON.stringify($this.$XLSX.utils.sheet_to_json(tempData.Sheets[tempData.SheetNames[0]]))
            $this.importExcelData($this.importData)
          };
          reader.readAsArrayBuffer(file);
          obj.value = null //防止多次导入同一个文件时函数不执行
        }
      },
    },
  }

</script>
<style Lang="less" scoped>
  * {
    color: #4b9100;
  }

  #checkPageButton {
    margin-right: 40px;
    width: 100px;
    height: 42px;
  }

  #checkPageButton+button {
    width: 100px;
    height: 42px;
  }

  .demo-table-expand {
    font-size: 10px;
  }

  .el-form>>>.el-form-item__label {
    width: 5rem;
    color: #000000;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 18%;
  }

  #searchDialog>>>.el-dialog__body {
    padding-top: 0;
    padding-bottom: 0;
  }

  #headerArea {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>